package cn.s1995.sloth.bizs.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.s1995.sloth.bizs.constant.BizCst;
import cn.s1995.sloth.bizs.entity.ImAccount;
import cn.s1995.sloth.bizs.exception.BizException;
import cn.s1995.sloth.bizs.mapper.ImAccountMapper;
import cn.s1995.sloth.bizs.service.ImAccountService;
import cn.s1995.sloth.bizs.util.im.TLSSigAPIv2;
import cn.s1995.sloth.common.core.constant.enums.UserTypeEnum;
import cn.s1995.sloth.common.core.constant.enums.hint.Hint;
import cn.s1995.sloth.common.security.service.SlothUser;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Random;
/**
 * IM账户
 *
 * @author sloth
 * @date 2024-01-09 14:13:30
 */
@Service
public class ImAccountServiceImpl extends ServiceImpl<ImAccountMapper, ImAccount> implements ImAccountService {

	@Value("${im.tencent.user_sig_expire}")
	private Long userSigExpire;

	@Value("${im.tencent.domain_name}")
	private String domainName;

	@Value("${im.tencent.sdk_app_id}")
	private long sdkappid;

	@Value("${im.tencent.identifier}")
	private String identifier;

	@Value("${global.oss-file-url}")
	private String ossFileUrl;

	@Resource
	private TLSSigAPIv2 api;

	@Override
	public String getImAccount(SlothUser user) {
		//在当前系统下bms和app的uid不会重复
		ImAccount account = this.getOne(
				Wrappers.lambdaQuery(ImAccount.class)
						.eq(ImAccount::getUid, user.getId())
						.eq(ImAccount::getPlatform, BizCst.IM.Account.Platform.tencent)
		);
		if(ObjectUtil.isNull(account))
			account = this.createImAccount(user);
		return account.getPlatformUid();
	}

	@Override
	public ImAccount createImAccount(SlothUser user) {
		Long uid = user.getId();
		//创建腾讯im账户
		//获取userSig
		String userSig = api.genUserSig(identifier, userSigExpire);
		Random random = new Random();
		String url = String.format("https://%s/v4/im_open_login_svc/account_import?sdkappid=%d&identifier=%s&usersig=%s&random=%d&contenttype=json", domainName, sdkappid, identifier, userSig, random.nextInt());
		JSONObject jsonObject = new JSONObject();
		jsonObject.set("UserID", uid.toString());
		jsonObject.set("Nick", user.getNickname());
		jsonObject.set("FaceUrl", ossFileUrl + user.getAvatar());
		try {
			HttpResponse response = HttpRequest.post(url)
					   .body(jsonObject.toJSONString(4))
					   .execute();
			if(response.getStatus() == 200) {
				JSONObject result = JSONUtil.parseObj(response.body());
				if(result.getInt("ErrorCode") == 0) {
					//成功，写入数据库
					ImAccount account = ImAccount.builder()
						.uid(uid)
						.userType(user.getUserType().equals(UserTypeEnum.TOB.getStatus())?BizCst.IM.Account.UserType.bms:BizCst.IM.Account.UserType.app)
						.platform(BizCst.IM.Account.Platform.tencent)
						.platformUid(uid.toString())
						.build();
					this.save(account);
					return account;
				}
			}
			//创建失败
			log.error(String.format("创建IM账号失败报文:%s", response.toString()));
			throw new BizException(Hint.APP_IM_ACCOUNT_CREATE_ERROR);
		} catch (Exception e) {
			log.error("创建IM账号失败", e);
			throw new BizException(Hint.APP_IM_ACCOUNT_CREATE_ERROR);
		}
	}
}
